"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/10/30
 */
import * as React from 'react'
import {WebViewProperties} from "react-native";

const {View, WebView} = require('react-native');
const {connect} = require('react-redux');
const patchPostMessageFunction = function () {
    const originalPostMessage = window.postMessage;

    const patchedPostMessage = function (message, targetOrigin, transfer) {
        originalPostMessage(message, targetOrigin, transfer);
    };

    patchedPostMessage.toString = function () {
        return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
    };

    window.postMessage = patchedPostMessage;
};

const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';
class MyWebView extends React.Component<WebViewProperties, any> {
    web:any;
    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            canGoBack:false,
            canGoForward:false,
            loading:false,
            title:'',
        };
        this.web = null;
    }
    onNavigationStateChange(e){
        console.log('onNavigationStateChange',e);

        this.setState({...e});
        this.props.onNavigationStateChange&&this.props.onNavigationStateChange(e);
    }
    onMessage(e){
        console.log('onMessage',e);
        this.props.onMessage&&this.props.onMessage(e);
    }
    onLoadEnd(e){
        console.log('onLoadEnd',e.nativeEvent);
        this.setState({...e.nativeEvent});
        this.props.onLoadEnd&&this.props.onLoadEnd(e);
    }

    render() {
        return (
            <View style={{display:'flex',flex: 1}}>
                <WebView style={{display:'flex',flex: 1}}
                         ref={web => { this.web = web; }}
                         injectedJavaScript={patchPostMessageJsCode}
                         javaScriptEnabled
                         domStorageEnabled
                         source={this.props.source}
                         onNavigationStateChange={this.onNavigationStateChange.bind(this)}
                         onMessage = {this.onMessage.bind(this)}
                         onLoadEnd = {this.onLoadEnd.bind(this)}
                />
            </View>

        );
    }
}

export default MyWebView;